<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>AMS配置页面</title>
    <style>
        *{
         margin: 0;
            padding: 0;
        }
        .overlay {
          position: fixed;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background-color: rgba(0, 0, 0, 0.5); /* 半透明灰色背景 */
          z-index: 9998; /* 设置一个较高的z-index值，比loader小1 */
        }
        .loader {
          border: 16px solid #f3f3f3; /* Light grey */
          border-top: 16px solid #3498db; /* Blue */
          border-radius: 50%;
          width: 120px;
          height: 120px;
          animation: spin 2s linear infinite;
          position: fixed;
          top: 48%;
          left: 48%;
          transform: translate(-50%, -50%);
          z-index: 9999; /* 设置一个较高的z-index值 */
          text-align: center; /* 文字居中 */
        }
        .loader-text {
          color: #fff; /* 白色文字 */
          font-size: 16px;
          margin-top: 60px; /* 调整文字位置 */
        }
        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }

        h1{
            text-align: center;
            margin: 10px 0;
        }
        ul{

            list-style: none;
        }
        button{
            background-color: #4CAF50; /* 绿色背景 */
            color: white; /* 白色文字 */
            padding: 5px 10px; /* 内边距 */
            text-align: center; /* 文字居中 */
            text-decoration: none; /* 取消下划线 */
            display: inline-block; /* 行内块元素 */
            font-size: 16px; /* 字体大小 */
            margin: 5px; /* 外边距 */
            cursor: pointer; /* 鼠标样式为手型 */
            border: none; /* 取消边框 */
            border-radius: 5px; /* 圆角 */
        }
        input{
            margin: 5px 0;
        }

        .box{
            width: 50%;
            margin: 100px auto;
           text-align: center
        }
        .status{
            width: 20px;
            height: 20px;
            border-radius: 25px;
            display: inline-block;
            background-color: red;
        }
        .color_span{
            margin: 5px;
            width: 20px;
            height: 20px;
            border-radius: 25px;
            display: inline-block;
            background-color: wheat;
            box-shadow: #6C6F73 1px 1px 1px 2px;
        }

          .status_true{
             background-color: green;
        }
        #mqtt{
            display: none;
        }
        .warring{
            color:red;}
        .change{
            background-color: #4CAF50;
            border-radius: 3px;
            margin: 0 10px;
            display: inline-block;
            width: 50px;
            color: white;
        }
    </style>
</head>

<body>
<div class="overlay">
    <div class="loader">
        <div class="loader-text">请求中....</div>
    </div>
</div>
<div class="box">
    <div>
        <p id="ip_addr">当前ip地址：</p>
        <p class="warring">消息</p>

    <h1>WIFI配置</h1>
    <h3>
        当前wifi连接状态：<span class="status"  id="wifi_status"></span><span id="wifi_statu_text">未连接</span>
    </h3>
    <ul id = "ssids">
        <li>请选择要连接WiFi名称</li>
    </ul>
     <ul>
         <li>密码<input type="password" name="wifi_password" ></li>
        <button class="myButton" onclick="connect_wifi()">确定连接wifi</button>
     </ul>


   <div id="mqtt">
        <h1>AMSmqtt配置</h1>
    <h3>当前mqtt连接状态：<span class="status" id="mqtt_status"></span><span id="mqtt_statu_text">未连接</span></h3>
        <div id="mqtt_info"></div>
        <button class="myButton"  onclick="connect_mqtt()">确定修改</button>
        <p>打印机通道设置</p>

       <div id="access_info">


       </div>
       <button class="myButton" onclick="access_set()" >确定修改</button>
           </div>
</div>
    </div>
 <script>
                // 获取加载动画元素和覆盖层元素
                var loader = document.querySelector('.loader');
                var overlay = document.querySelector('.overlay');
                loader.style.display = 'none';
                overlay.style.display = 'none';
                document.documentElement.style.overflow = 'auto'
                function loader_s(is_open=true){
                    if(is_open){
                        loader.style.display = 'block';
                        overlay.style.display = 'block';
                        document.documentElement.style.overflow = 'hidden';
                    }else{
                        loader.style.display = 'none';
                        overlay.style.display = 'none';
                        document.documentElement.style.overflow = 'auto';
                    }
                }
                var wifi_status = document.getElementById('wifi_status');
                var mqtt_div = document.getElementById('mqtt');
                if(wifi_status.classList.contains('status_true')){
                    mqtt_div.style.display='block'
                }
                var observer = new MutationObserver(function(mutationsList) {
                    mutationsList.forEach(function(mutation) {
                        if (mutation.attributeName === 'class' && wifi_status.classList.contains('status_true')) {
                            mqtt_div.style.display='block'

                        }
                    });
                    });
                // 配置MutationObserver监视span元素的属性变化
                observer.observe(wifi_status, { attributes: true });

                function connect_wifi_event(data){
                    document.getElementById('wifi_status').classList.add("status_true")
                    document.getElementById('wifi_statu_text').innerText="已连接"
                    get_ip_data(data)
                    alert("wifi连接成功"+data["info"])
                }
                function connect_wifi(){
                    const jsonData = {
                        name: selectedRadioButton = document.querySelector('input[name="wifi_name"]:checked').value,
                        password: document.querySelector('input[name="wifi_password"]').value,
                    };

                    send_data("/wifi_connect",jsonData,connect_wifi_event)
                }
                function connect_mqtt_event(data){
                    document.getElementById('mqtt_status').classList.add("status_true")
                    document.getElementById('mqtt_statu_text').innerText="已连接"+data["info"]
                    alert("mqtt连接成功:"+data["info"])
                }
                function connect_mqtt(){
                    const jsonData = {
                        mqtt_server: document.querySelector('input[name="mqtt_server"]').value,
                        DEVICE_SERIAL: document.querySelector('input[name="DEVICE_SERIAL"]').value,
                        mqtt_password: document.querySelector('input[name="mqtt_password"]').value,
                        client_id: document.querySelector('input[name="client_id"]').value,
                        username: document.querySelector('input[name="username"]').value,
                        mqtt_port: document.querySelector('input[name="mqtt_port"]').value,
                    };
                    send_data("/mqtt_connect",jsonData,connect_mqtt_event)
                }
                function connect_access_set_event(data){
                    alert("通道设置成功:"+data["info"])
                }
                function access_set(){
                    const access_list = [];
                    var filamentInputs = document.getElementsByClassName('fileament_class')
                    for (var i = 0; i < filamentInputs.length; i++) {
                                var value = filamentInputs[i].value;
                                access_list.push(parseInt(value))
                            }

                    const color_list =  []
                    const color_span = document.getElementsByClassName("color_span")
                    for (var i = 0; i < color_span.length; i++) {
                        var value2 = color_span[i].style.backgroundColor
                        color_list.push(value2)
                    }
                    const jsonData = {
                        access_list:access_list,
                        color_list:color_list
                    }
                    console.log(jsonData)
                    send_data("/access_set",jsonData,connect_access_set_event)
                }
                function send_data(url,data,event_fun){
                    loader_s()
                    const requestOptions = {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Access-Control-Allow-Origin':'*'
                        },
                        body: JSON.stringify(data)
                    };
                    fetch(url, requestOptions)
                        .then(response => {
                            if (!response.ok) {
                                return response.json().then(errorData => {
                                throw new Error(errorData.info);
                                                }); }
                            return response.json();
                        })
                        .then(data => {
                            event_fun(data)
                            loader_s(false)
                        })
                        .catch(error => {
                            loader_s(false);
                            alert('出现问题'+ error)
                        });

                }
                // 获取wifi信息
                function get_wifi_info(data){
                    const status_span = document.getElementById("wifi_status");
                    const wifi_statu_text_span = document.getElementById("wifi_statu_text");
                    if("wifi_isconnected" in data){
                        if(data["wifi_isconnected"]){
                            status_span.classList.add("status_true");
                            wifi_statu_text_span.innerText = "已连接"

                        }
                        const ssids_ul = document.getElementById("ssids");
                        for(var ssid of data["ssids"]){
                            ssids_ul.innerHTML += '<li><input type="radio" name="wifi_name" value="'+ssid+'">'+ssid+'</li>'
                        }
                    }

                }
                // 获取mqtt信息
                function get_mqtt_data(data){
                    const status_span = document.getElementById("mqtt_status");
                    const mqtt_statu_text_span = document.getElementById("mqtt_statu_text");
                    if("is_mqtt_con" in data){
                        if(data["is_mqtt_con"]){
                            status_span.classList.add("status_true");
                            mqtt_statu_text_span.innerText = "已连接"
                        }
                        const mqtt_info_div = document.getElementById("mqtt_info");
                        mqtt_info_div.innerHTML = '打印机ip地址：<input name="mqtt_server" type="text" value="'+data["mqtt_server"]+'" ><br>\n' +
                            '        打印机序列号：<input name="DEVICE_SERIAL" type="text" value="'+data["DEVICE_SERIAL"]+'"><br>\n' +
                            '        打印机密码：<input name="mqtt_password" type="password" value="'+data["mqtt_password"]+'"><br>\n' +
                            '        MQTT客户端名称：<input name="client_id" type="text" value="'+data["client_id"]+'"><br>\n' +
                            '        MQTT服务端名称：<input name="username" type="text" value="'+data["username"]+'"><br>\n' +
                            '        MQTT端口：<input name="mqtt_port" type="number" value="'+data["mqtt_port"]+'"><br>'

                    }
                }
                // 获取通道信息
                function get_access_data(data){
                    const access_info_div = document.getElementById("access_info");
                    for(let n = 0; n<data["access_list"].length; n++){
                        const item_div = document.createElement("div")

                        item_div.innerHTML+= '<span onclick="opthon_color(this)" id="color'+data["access_list"][n]+'" class="color_span" style="background-color: '+  data["color_list"][n]+'" ></span>'

                        item_div.innerHTML += '料盘'+(n+1)+': <input class="fileament_class" name="access'+(data["access_list"][n])+'" type="number" value="'+(data["access_list"][n])+'">'
                        if(data["access_list"][n]==data["current_access"]){
                            item_div.innerHTML+='<input type="button"  value="退料" class="change" style="background-color: #007bff">'
                        }else {
                            item_div.innerHTML+='<input type="button"  value="换料"   class="change">'
                        }

                        access_info_div.append(item_div)
                    }

                }
                function get_ip_data(data){
                    ip_p =document.getElementById("ip_addr");
                    console.log(data["ip"])
                    ip_p.innerText = "当前ip地址："+ data["ip"]
                }

                send_data("/get_ip_info",{},get_ip_data)
                send_data("/get_wifi_info",{},get_wifi_info)
                send_data("/get_mqtt_info",{},get_mqtt_data)
                send_data("/get_access_info",{},get_access_data)
                function opthon_color(event){
                    // 创建一个颜色输入框，type="color" 会弹出颜色选择器
                    const colorInput = document.createElement('input');
                     colorInput.style.position = 'absolute';
                    colorInput.style.left = '50%';
                    colorInput.style.top = '50%';
                    colorInput.style.transform = 'translate(-50%, -50%)'
                    colorInput.type = 'color';
                    colorInput.addEventListener('change', function () {
                        const selectedColor = colorInput.value;
                        event.style.backgroundColor = selectedColor;
                    });

                    // 模拟点击颜色输入框，弹出颜色选择器
                    colorInput.click();
                }

        </script>
        </body>
        </html>